package com.goldplusgold.tradedelay.app.home.live.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.goldplusgold.imageloader.lib.IShow;
import com.goldplusgold.live.LVDataManager;
import com.goldplusgold.live.bean.LMessageBean;
import com.goldplusgold.live.channel.LiveBootstrap;
import com.goldplusgold.live.channel.ResponseHandler;
import com.goldplusgold.live.result.ResultMessages;
import com.goldplusgold.network.lib.http.netty.ChannelBootstrapManager;
import com.goldplusgold.support.lib.utils.BitmapUtil;
import com.goldplusgold.support.lib.utils.ScreenSizeUtil;
import com.goldplusgold.support.lib.widget.VerticalTimeLine;
import com.goldplusgold.tradedelay.app.R;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2017/8/4.
 */

public class ReTextLiveAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    public static final int TEXT_LIVE_ITEM = 0 ;
    public static final int TEXT_IMAGE_ITEM = 1 ;
    public static final int TEXT_VIDEO_ITEM = 2 ;

    private Context context;
    List<LMessageBean> datas = new ArrayList<>();
    String roomID;
    private int liveStatus ;
    int count = 10;
    Bitmap videoBitmap;
    Bitmap bitmap ;
    int mBitmapHight ;
    int mBitmapWidth ;
    private LiveBootstrap liveBootstrap ;
    private  ResponseHandler.ReceiverMessageInterface receiverMessageInterface ;

    public ReTextLiveAdapter(Context mContext, String roomID , int liveStatus) {
        this.context = mContext;
        this.roomID = roomID;
        this.liveStatus = liveStatus ;
        if(liveStatus == 30) {
            receiverMessageInterface = new ResponseHandler.ReceiverMessageInterface() {
                @Override
                public void onReceiver(final LMessageBean bean) {
                    insertData(bean);
                }

                @Override
                public void onTakeBack(String id) {
                    takeBack(id);
                }
            };
            liveBootstrap = new LiveBootstrap(roomID, receiverMessageInterface);
            ChannelBootstrapManager.getInstance().register(liveBootstrap.hashCode() + "", liveBootstrap);
        }
        if(liveStatus != 0 && liveStatus != 20) {
            requestData();
        }
    }

    private void takeBack(String id) {
        for(LMessageBean bean:datas){
            if(bean.getId().equals(id)){
                datas.remove(bean);
                break;
            }
        }

        ((Activity)context).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                notifyDataSetChanged();
            }
        });
    }

    public void pullUp(){
        if(datas.size() >= count){
            count = count +10;
            requestData();
        }
    }

    private void requestData() {
        LVDataManager.getInstance().getHistoryMessages(roomID, "", count, new Callback<ResultMessages>() {
            @Override
            public void onResponse(Call<ResultMessages> call, Response<ResultMessages> response) {
                setDatas(response.body().getMessages());
            }

            @Override
            public void onFailure(Call<ResultMessages> call, Throwable t) {

            }
        });
    }

    public void setDatas(List<LMessageBean> datas) {
        if(datas != null && datas.size() > 0){
            this.datas = datas;
        }
        notifyDataSetChanged();
    }

    private void insertData(LMessageBean bean) {
        datas.add(0, bean);
        ((Activity)context).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                notifyDataSetChanged();
            }
        });
    }



    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = null;
        switch (viewType){
            case TEXT_LIVE_ITEM:
                itemView = LayoutInflater.from(context).inflate(R.layout.item_text_live , parent ,false);
                return new TextHolder(itemView);
            case TEXT_IMAGE_ITEM:
                itemView = LayoutInflater.from(context).inflate(R.layout.item_text_image_live , parent ,false);
                return new TextAndImageHolder(itemView);
            case TEXT_VIDEO_ITEM:
                itemView = LayoutInflater.from(context).inflate(R.layout.item_text_mp4_live , parent ,false);
                return new TextAndMP4Holder(itemView);
            default:
                return null;
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        if(holder instanceof TextHolder){
            TextHolder h = (TextHolder) holder;
            bindTextData(position , h);
        }
        if(holder instanceof TextAndImageHolder){
            TextAndImageHolder h = (TextAndImageHolder) holder;
            bindImageData(position , h);
        }

        if(holder instanceof TextAndMP4Holder){
            TextAndMP4Holder h = (TextAndMP4Holder) holder;
            h.itemView.setTag(position);
            bindMp4Data(position , h);
        }

    }

    private void bindMp4Data(int position, final TextAndMP4Holder h) {
        long lt = new Long(datas.get(position).getTime());
        Date date = new Date(lt);
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
        final String dateString = formatter.format(date);
        h.mTimeLine.setPosition(position);
        h.mTimeLine.setTime(dateString);
        h.mInfoTextView.setText(datas.get(position).getContent());

        final LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) h.live_text_mp4_layout.getLayoutParams();
        ViewTreeObserver viewTreeObserver = h.live_text_mp4_layout.getViewTreeObserver();
        viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                int timeHeight = h.live_text_mp4_layout.getHeight() +params.topMargin + params.bottomMargin ;
                h.mTimeLine.setSize(timeHeight);
                h.live_text_mp4_layout.getViewTreeObserver().removeOnPreDrawListener(this);
                return true;
            }
        });
    }

    private void bindTextData(int position, final TextHolder h) {
        long lt = new Long(datas.get(position).getTime());
        Date date = new Date(lt);
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
        final String dateString = formatter.format(date);
        h.mTimeLine.setPosition(position);
        h.mTimeLine.setTime(dateString);

        h.mInfoTextView.setText(datas.get(position).getContent());
        final LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) h.mInfoTextView.getLayoutParams();
        ViewTreeObserver viewTreeObserver = h.mInfoTextView.getViewTreeObserver();
        viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                int timeHeight = h.mInfoTextView.getHeight() +params.topMargin + params.bottomMargin ;
                h.mTimeLine.setSize(timeHeight);
                h.mInfoTextView.getViewTreeObserver().removeOnPreDrawListener(this);
                return true;
            }
        });
    }

    private void bindImageData(int position, final TextAndImageHolder h) {
        long lt = new Long(datas.get(position).getTime());
        Date date = new Date(lt);
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
        final String dateString = formatter.format(date);
        h.mTimeLine.setPosition(position);
        h.mTimeLine.setTime(dateString);


        h.mInfoTextView.setText(datas.get(position).getContent());
        String imageUri = datas.get(position).getMediaUri() ;
        int start = imageUri.lastIndexOf("/");
        int end = imageUri.length();
        String fileName = imageUri.substring(start + 1, end);
        int begin = fileName.lastIndexOf("_");
        int finish = fileName.lastIndexOf(".");
        String widthHeight = fileName.substring(begin + 1, finish);
        String[] imageInfos = widthHeight.split("x");
        if (imageInfos.length != 2) {
            return;
        }
        final int imageWidth = Integer.parseInt(imageInfos[0]);
        final int imageHeight = Integer.parseInt(imageInfos[1]);
        int width = ScreenSizeUtil.dip2px(context, imageWidth);
        int height = ScreenSizeUtil.dip2px(context, imageHeight);

        int screenWidth = (int) (ScreenSizeUtil.getDeviceWidth((Activity) context) * 0.6);
        if(width > screenWidth ){
            height = screenWidth * height / width ;
            width = screenWidth ;
        }

        LinearLayout.LayoutParams p =  new LinearLayout.LayoutParams(width , height);
        h.mImageView.setLayoutParams(p);

        Glide.with(context).load(imageUri).into(h.mImageView);

        final LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) h.live_text_image_layout.getLayoutParams();
        ViewTreeObserver viewTreeObserver = h.live_text_image_layout.getViewTreeObserver();
        viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                int timeHeight = h.live_text_image_layout.getHeight() +params.topMargin + params.bottomMargin ;
                h.mTimeLine.setSize(timeHeight);
                h.live_text_image_layout.getViewTreeObserver().removeOnPreDrawListener(this);
                return true;
            }
        });
    }

    @Override
    public int getItemCount() {
        if (datas != null) {
            return datas.size();
        }
        return 0;
    }

    @Override
    public int getItemViewType(int position) {
        int type = datas.get(position).getMediaType() ;
        if(type > 12 && type < 34) {
            return TEXT_VIDEO_ITEM;
        }else if(type > 0 && type < 12 && !TextUtils.isEmpty(datas.get(position).getMediaUri()) ){
            return TEXT_IMAGE_ITEM;
        }else{
            return TEXT_LIVE_ITEM;
        }
    }

    public class TextHolder extends RecyclerView.ViewHolder{

        @BindView(R.id.item_live_text_time)
        VerticalTimeLine mTimeLine ;

        @BindView(R.id.live_detail_listview_info)
        TextView mInfoTextView ;


        public TextHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this , itemView);
        }

    }

    public class TextAndImageHolder extends RecyclerView.ViewHolder{
        @BindView(R.id.live_text_image_time)
        VerticalTimeLine mTimeLine ;

        @BindView(R.id.live_text_image_info)
        TextView mInfoTextView ;

        @BindView(R.id.live_text_image_img)
        ImageView mImageView ;

        @BindView(R.id.live_text_image_layout)
        LinearLayout live_text_image_layout ;

        public TextAndImageHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this , itemView);
        }

    }

    public class TextAndMP4Holder extends RecyclerView.ViewHolder{
        @BindView(R.id.live_text_mp4_time)
        VerticalTimeLine mTimeLine ;

        @BindView(R.id.live_text_mp4_info)
        TextView mInfoTextView ;

        @BindView(R.id.live_text_mp4_img)
        ImageView mImageView ;

        @BindView(R.id.live_text_mp4_layout)
        LinearLayout live_text_mp4_layout ;

        public TextAndMP4Holder(final View itemView) {
            super(itemView);
            ButterKnife.bind(this , itemView);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    int pos = (int) itemView.getTag();
                    int type = datas.get(pos).getMediaType();
                    if(type > 12 && type < 34) {
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        String url = datas.get(pos).getMediaUri();
                        intent.setDataAndType(Uri.parse(url), "video/mp4");
                        try {
                            context.startActivity(intent);
                        }catch (Exception e){
                            Toast.makeText(context, "您未安装播放器~", Toast.LENGTH_SHORT).show();
                        }

                    }
                }
            });
        }

    }



    public void onChannleCancel(){
        if(liveStatus == 30) {
            receiverMessageInterface = null;
            ChannelBootstrapManager.getInstance().unregister(liveBootstrap.hashCode() + "");
            liveBootstrap = null;
        }
    }

}
